package com.example.texted.completablefuture;

import org.junit.Test;

import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

public class Do {
    public static void main(String[] args) throws Exception {
        // 创建异步执行任务:
        CompletableFuture<Double> cf = CompletableFuture.supplyAsync(Do::fetchPrice);
        // 如果执行成功:
//        cf.get();
        cf.thenAccept((result) -> {
            System.out.println("thenAccept"+Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("thenAccept price: " + result+Thread.currentThread().getName());
        });
        cf.whenComplete((result,e1) -> {
            System.out.println("whenComplete"+Thread.currentThread().getName());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("whenComplete price: " + result+Thread.currentThread().getName());
        });
        // 如果执行异常:
        cf.exceptionally((e) -> {
            e.printStackTrace();
            return null;
        });
//        System.out.println(cf.get()+Thread.currentThread().getName());
        System.out.println(11111+Thread.currentThread().getName());
        // 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:
        Thread.sleep(5000);
    }

    static Double fetchPrice() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ignored) {
        }
        if (Math.random() < 0.1) {
            throw new RuntimeException("fetch price failed!");
        }
        return 5 + Math.random() * 20;
    }


    static class TaskSupplier implements Supplier<String> {
        private String who;
        public TaskSupplier(String who){
            super();
            this.who=who;
        }

        @Override
        public String get() {
            System.out.println("task is running");
            return   "Hello,"+who;
        }
    }
    @Test
    public void testCompletableFuture() throws Exception{
        CompletableFuture<String> future  = CompletableFuture.supplyAsync(new TaskSupplier("陈大文"));
        future.whenCompleteAsync((s,ex)->{
            System.out.println("4 b:"+s);
        });
        System.out.println("1 do somthing ...");
        System.out.println("2 c:"+future.get());
        System.out.println("3 end.");
        
    }
}
